package com.kim.common.Snowflakes;

import com.kim.common.Snowflakes.key.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.UUID;

/**
 * @author ZhouChuGang
 * @version 1.0
 * @project langangkj-commonm
 * @date 2020/5/4 15:48
 * @Description ID生成工具类
 */
@Slf4j
public class IdGenerateUtils {
    private static final SnowflakeIdWorker SNOWFLAKE_ID_WORKER;

    static {
        Random random = new Random();
        SNOWFLAKE_ID_WORKER = new SnowflakeIdWorker(random.nextInt(20) + 1, random.nextInt(20) + 1);
    }

    private IdGenerateUtils() {

    }


    /**
     * 得到雪花算法对象
     *
     * @return
     */
    public static SnowflakeIdWorker getSnowflakeIdWorker() {
        return SNOWFLAKE_ID_WORKER;
    }

    private static String strLimitLength(String str, int len) {
        if (str == null || str.length() == 0 || len == 0) {
            return "";
        }
        if (len < 0 || len >= str.length()) {
            return str;
        }
        return str.substring(0, len);
    }


    /**
     * 通过uuid的生成ID
     *
     * @param len      要生成的长度
     * @param compress 是否压缩
     * @return
     */
    public static String generateIdByUUid(int len, boolean compress) {
        String uuid = compress ? UUID.randomUUID().toString().replaceAll("-", "") : UUID.randomUUID().toString();
        return strLimitLength(uuid, len);
    }

    /**
     * 通过uuid的生成ID
     *
     * @param compress 是否压缩
     * @return
     */
    public static String generateIdByUUid(boolean compress) {
        return generateIdByUUid(-1, compress);
    }

    /**
     * 通过雪花算法生成 id
     *
     * @param len
     * @return
     */
    public static String generateIdBySnowflake(int len) {
        String nextId = SNOWFLAKE_ID_WORKER.nextId() + "";
        return strLimitLength(nextId, len);
    }


    /**
     * 通过雪花算法生成 id
     *
     * @return
     */
    public static String generateIdBySnowflake() {
        return generateIdBySnowflake(-1);
    }

}
